package com.jp.knowledge.my.activity;

import android.content.Intent;
import android.net.Uri;
import android.support.v4.widget.NestedScrollView;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.SelectModel;
import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.ClipImageActivity;
import com.jp.knowledge.activity.ImagePickerIntent;
import com.jp.knowledge.activity.OrganizeKnowledgeSelectActivity;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.AreaModel;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.OrganizeInfoModel;
import com.jp.knowledge.service.SaveOrganizeInfoService;
import com.jp.knowledge.service.SaveUserDataService;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.ClipViewLayout;
import com.jp.knowledge.view.FlowLayout;

import org.xutils.view.annotation.ViewInject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/7/31.
 */

public class OrganizeInfoActivity extends SlidingActivity implements View.OnClickListener, ResultSubscriber.OnResultListener {

	private static final int SELECT_LOGO_CODE = 0x01;
	private static final int REQUEST_CROP_PHOTO = 0x02;
	private static final int SELECT_KNOWLEDGE_CODE = 0x03;

	private String companyId;
	private int companyType;
	private OrganizeInfoModel organizeInfoModel;
	private OrganizeInfoModel changeModel;

	@ViewInject(R.id.contentScrollView)
	private NestedScrollView contentScrollView;
	@ViewInject(R.id.info_item_logo)
	private LinearLayout itemLogo;
	@ViewInject(R.id.info_item_logo_icon)
	private ImageView itemLogoIcon;
	@ViewInject(R.id.info_item_simpale_name)
	private LinearLayout itemSimpleName;
	@ViewInject(R.id.info_item_simpale_name_desc)
	private TextView itemSimpleNameDesc;
	@ViewInject(R.id.info_item_fill_name)
	private LinearLayout itemFillName;
	@ViewInject(R.id.info_item_fill_name_desc)
	private TextView itemFillNameDesc;
	@ViewInject(R.id.info_item_phone)
	private LinearLayout itemPhone;
	@ViewInject(R.id.info_item_phone_desc)
	private TextView itemPhoneDesc;
	@ViewInject(R.id.info_item_website)
	private LinearLayout itemWebsite;
	@ViewInject(R.id.info_item_website_desc)
	private TextView itemWebsiteDesc;
	@ViewInject(R.id.info_item_email)
	private LinearLayout itemEmail;
	@ViewInject(R.id.info_item_email_desc)
	private TextView itemEmailDesc;
	@ViewInject(R.id.info_item_people_num)
	private LinearLayout itemPeopleNum;
	@ViewInject(R.id.info_item_people_num_desc)
	private TextView itemPeopleNumDesc;
	@ViewInject(R.id.info_item_local)
	private LinearLayout itemLocal;
	@ViewInject(R.id.info_item_local_desc)
	private TextView itemLocalDesc;
	@ViewInject(R.id.info_item_address)
	private LinearLayout itemAddress;
	@ViewInject(R.id.info_item_address_desc)
	private TextView itemAddressDesc;
	@ViewInject(R.id.info_knowledge_select)
	private ImageView knowledgeSelectBtn;
	@ViewInject(R.id.info_knowledge_view)
	private FlowLayout knowledgeView;

	private OptionsPickerView pickerView;
	private List<String> provinceList;
	private List<List<String>> cityList;
	private List<List<List<String>>> areaList;

	@Override
	protected int getResourceId() {
		return R.layout.activity_organize_info;
	}

	@Override
	protected void init() {
		companyId = getIntent().getStringExtra("companyId");
		companyType = getIntent().getIntExtra("companyType", 1);
		changeModel = new OrganizeInfoModel();
		changeModel.setCompanyid(companyId);
		changeModel.setCompanytype(companyType);
		initView();
		getData();
	}

	private void initView(){
		topName.setText("企业档案");
		rightIcon.setVisibility(View.GONE);
		leftIcon.setImageResource(R.mipmap.guanzhufanhui);
		leftIcon.setOnClickListener(this);
		itemLogo.setOnClickListener(this);
		itemSimpleName.setOnClickListener(this);
		itemFillName.setOnClickListener(this);
		itemPhone.setOnClickListener(this);
		itemWebsite.setOnClickListener(this);
		itemEmail.setOnClickListener(this);
		itemPeopleNum.setOnClickListener(this);
		itemLocal.setOnClickListener(this);
		itemAddress.setOnClickListener(this);
		knowledgeSelectBtn.setOnClickListener(this);

		initPickerView();
	}

	private void initPickerView(){
		provinceList = new ArrayList<>();
		cityList = new ArrayList<>();
		areaList = new ArrayList<>();

		OptionsPickerView.OnOptionsSelectListener optionsSelectListener = new OptionsPickerView.OnOptionsSelectListener() {
			@Override
			public void onOptionsSelect(int options1, int options2, int options3, View v) {
				String province = provinceList.get(options1);
				String city = cityList.get(options1).get(options2);
				String area = areaList.get(options1).get(options2).get(options3);
				itemLocalDesc.setText(province+city+area);
				changeModel.setProvince(province);
				changeModel.setCity(city);
				changeModel.setArea(area);
			}
		};

		pickerView = new OptionsPickerView.Builder(mContext, optionsSelectListener)
				.setDividerColor(getResources().getColor(R.color.gray_deep))
				.setCyclic(true, true, true)
				.isCenterLabel(false)
				.build();

		Observable.create(new Observable.OnSubscribe<Void>() {
			@Override
			public void call(Subscriber subscriber) {
				try {
					InputStreamReader inputReader = new InputStreamReader(mContext
							.getResources().getAssets().open("area.json"));
					BufferedReader bufReader = new BufferedReader(inputReader);
					String line;
					StringBuilder sb = new StringBuilder();
					while ((line = bufReader.readLine()) != null)
						sb.append(line);
					List<AreaModel> areaModels = JsonUtil.getInstance()
							.jsonArrayToObject(sb.toString(), AreaModel.class);
					bufReader.close();
					inputReader.close();
					if(areaModels == null)
						return;
					areaList.clear();
					cityList.clear();
					provinceList.clear();
					for(AreaModel areaModel : areaModels){
						List<String> cityNameList = new ArrayList<>();
						List<AreaModel.CityBean> cityBeen = areaModel.getCity();
						List<List<String>> areaTmpList = new ArrayList<>();
						for(AreaModel.CityBean cityBean : cityBeen) {
							cityNameList.add(cityBean.getName());
							List<String> areaNameList = new ArrayList<>();
							List<AreaModel.CityBean.DistrictBean> areaBeen = cityBean.getDistrict();
							for(AreaModel.CityBean.DistrictBean areaBean : areaBeen)
								areaNameList.add(areaBean.getName());
							areaTmpList.add(areaNameList);
						}
						areaList.add(areaTmpList);
						cityList.add(cityNameList);
						provinceList.add(areaModel.getName());
					}
					subscriber.onNext(null);
					subscriber.onCompleted();
				} catch (IOException e) {
					subscriber.onError(e);
				}
			}
		}).subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Subscriber<Void>() {
			@Override
			public void onCompleted() {}
			@Override
			public void onError(Throwable e) {}
			@Override
			public void onNext(Void aVoid) {
				pickerView.setPicker(provinceList, cityList, areaList);
			}
		});
	}

	private void setView(OrganizeInfoModel organizeInfoModel){
		if(organizeInfoModel == null){
			contentScrollView.setVisibility(View.GONE);
		} else {
			contentScrollView.setVisibility(View.VISIBLE);
			ImageLoadUtil.loadCircle(this, organizeInfoModel.getCompanyicon(), itemLogoIcon);
			itemSimpleNameDesc.setText(organizeInfoModel.getCompanyname());
			itemFillNameDesc.setText(organizeInfoModel.getCompanyfullname());
			itemPhoneDesc.setText(organizeInfoModel.getCompanyphone());
			itemWebsiteDesc.setText(organizeInfoModel.getCompanyhttp());
			itemEmailDesc.setText(organizeInfoModel.getEmail());
			itemPeopleNumDesc.setText(organizeInfoModel.getEmployeesnum());
			String local = "";
			if (organizeInfoModel.getProvince() != null)
				local += organizeInfoModel.getProvince();
			if (organizeInfoModel.getCity() != null)
				local += organizeInfoModel.getCity();
			if (organizeInfoModel.getArea() != null)
				local += organizeInfoModel.getArea();
			itemLocalDesc.setText(local);
			itemAddressDesc.setText(organizeInfoModel.getAddress());
			setKnowledgeView(organizeInfoModel.getKnowledge());
		}
	}

	private void setKnowledgeView(List<OrganizeInfoModel.KnowledgeBean> datas){
		knowledgeView.removeAllViews();
		if(datas == null)
			return;
		for(OrganizeInfoModel.KnowledgeBean data : datas){
			TextView textView = new TextView(this);
			textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.min_font));
			textView.setGravity(Gravity.CENTER);
			textView.setText(data.getCateName());
			textView.setTextColor(getResources().getColor(R.color.font_gray_deep));
			textView.setBackground(getResources().getDrawable(R.drawable.btn_rbg_gray));
			textView.setPadding((int)(getResources().getDimension(R.dimen.space_middle)+0.5),
					(int)(getResources().getDimension(R.dimen.space_min)+0.5),
					(int)(getResources().getDimension(R.dimen.space_middle)+0.5),
					(int)(getResources().getDimension(R.dimen.space_min)+0.5));
			knowledgeView.addView(textView);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode != RESULT_OK || data == null)
			return;
		if(requestCode == SELECT_LOGO_CODE){
			List<String> imageSelectedPaths = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
			if(imageSelectedPaths == null && imageSelectedPaths.size() == 0)
				return;
			Uri uri = Uri.parse(imageSelectedPaths.get(0));
			gotoClipActivity(uri, 2);
		} else if(requestCode == REQUEST_CROP_PHOTO){
			Uri uri = data.getData();
			if(uri != null) {
				String icon = ClipViewLayout.getRealFilePathFromUri(mContext, uri);
				changeModel.setCompanyicon(icon);
				ImageLoadUtil.loadCircle(mContext, icon, itemLogoIcon);
			}
		} else if(requestCode == SELECT_KNOWLEDGE_CODE){
			List<OrganizeInfoModel.KnowledgeBean> knowledges = (List) data.getSerializableExtra("data");
			setKnowledgeView(knowledges);
			changeModel.setKnowledge(knowledges);
		} else if(requestCode == UserSettingEditActivity.REQUEST_CODE){
			String resultData = data.getStringExtra(UserSettingEditActivity.RESULT_DATA);
			switch (data.getIntExtra(UserSettingEditActivity.VIEW_ID, 0x00)) {
				case R.id.info_item_simpale_name:		// 企业简称
					itemSimpleNameDesc.setText(resultData);
					changeModel.setCompanyname(resultData);
					break;
				case R.id.info_item_fill_name:			// 企业全称
					itemFillNameDesc.setText(resultData);
					changeModel.setCompanyfullname(resultData);
					break;
				case R.id.info_item_phone:				// 企业电话
					itemPhoneDesc.setText(resultData);
					changeModel.setCompanyphone(resultData);
					break;
				case R.id.info_item_website:				// 企业网址
					itemWebsiteDesc.setText(resultData);
					changeModel.setCompanyhttp(resultData);
					break;
				case R.id.info_item_email:				// 企业邮箱
					itemEmailDesc.setText(resultData);
					changeModel.setEmail(resultData);
					break;
				case R.id.info_item_people_num:			// 员工人数
					itemPeopleNumDesc.setText(resultData);
					changeModel.setEmployeesnum(resultData);
					break;
				case R.id.info_item_address:				// 详细地址
					itemAddressDesc.setText(resultData);
					changeModel.setAddress(resultData);
					break;
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()){
			case R.id.icon_left:
				onBackPressed();
				break;
			case R.id.info_item_logo:
				gotoSelectLogo();
				break;
			case R.id.info_item_simpale_name:
				UserSettingEditActivity.gotoEdit(this, R.id.info_item_simpale_name,
						"设置企业简称", organizeInfoModel.getCompanyname(), "输入企业简称");
				break;
			case R.id.info_item_fill_name:
				UserSettingEditActivity.gotoEdit(this, R.id.info_item_fill_name,
						"设置企业全称", organizeInfoModel.getCompanyfullname(), "输入企业全称");
				break;
			case R.id.info_item_phone:
				UserSettingEditActivity.gotoEdit(this, R.id.info_item_phone,
						"设置固定电话", organizeInfoModel.getCompanyphone(),
						"输入固定电话", UserSettingEditActivity.TYPE_PHONE);
				break;
			case R.id.info_item_website:
				UserSettingEditActivity.gotoEdit(this, R.id.info_item_website,
						"设置官方网站", organizeInfoModel.getCompanyhttp(),
						"输入官方网站", UserSettingEditActivity.TYPE_WEB);
				break;
			case R.id.info_item_email:
				UserSettingEditActivity.gotoEdit(this, R.id.info_item_email,
						"设置官方邮箱", organizeInfoModel.getEmail(),
						"输入官方邮箱", UserSettingEditActivity.TYPE_MAIL);
				break;
			case R.id.info_item_people_num:
				UserSettingEditActivity.gotoEdit(this, R.id.info_item_people_num,
						"设置员工人数", organizeInfoModel.getEmployeesnum(),
						"输入员工人数", UserSettingEditActivity.TYPE_INT);
				break;
			case R.id.info_item_local:
				pickerView.show();
				break;
			case R.id.info_item_address:
				UserSettingEditActivity.gotoEdit(this, R.id.info_item_address,
						"设置详细地址", organizeInfoModel.getAddress(), "输入详细地址");
				break;
			case R.id.info_knowledge_select:
				Intent intent = new Intent(mContext, OrganizeKnowledgeSelectActivity.class);
				intent.putExtra("data", (Serializable) organizeInfoModel.getKnowledge());
				startActivityForResult(intent, SELECT_KNOWLEDGE_CODE);
				break;
		}
	}

	private void gotoSelectLogo(){
		ImagePickerIntent intent = new ImagePickerIntent(this);
		intent.setSelectModel(SelectModel.MULTI);
		intent.setMaxTotal(1);
		intent.setShowCarema(true);
		startActivityForResult(intent, SELECT_LOGO_CODE);
		overridePendingTransition(R.anim.anim_enter, 0);
	}

	public void gotoClipActivity(Uri uri, int type) {
		if (uri == null)
			return;
		Intent intent = new Intent();
		intent.setClass(this, ClipImageActivity.class);
		intent.putExtra("type", type);
		intent.setData(uri);
		startActivityForResult(intent, REQUEST_CROP_PHOTO);
	}

	private void getData(){
		JsonObject param = new JsonObject();
		param.addProperty("companyid", companyId);
		param.addProperty("companytype", companyType);
		HttpHelper.getInstance(mContext).organizaInfo(param, 0x01, this);
	}

	@Override
	public void finish() {
		saveData();
		super.finish();
	}

	private void saveData(){
		startService(new Intent(this, SaveOrganizeInfoService.class)
				.putExtra("data", changeModel)
				.putExtra("originalData", organizeInfoModel));
	}

	@Override
	public void onStart(int requestType) {
		loading.show();
	}

	@Override
	public void onCompleted(int requestType) {
		loading.cancel();
	}

	@Override
	public void onError(int requestType) {
		onCompleted(requestType);
	}

	@Override
	public void onNext(IModel data, int requestType) {
		if(data.getErrcode() != 0){
			ToasUtil.toast(mContext, data.getMessage());
			onError(requestType);
		} else{
			organizeInfoModel = data.getEntity(OrganizeInfoModel.class);
			setView(organizeInfoModel);
		}
	}
}
